<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Div跟随鼠标移动</title>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        #box1{
            width: 100px;
            height: 100px;
            background-color: rgba(128, 255, 0, 0.74);
            position: absolute;
        }
        body{
            width: 2000px;
            height: 1000px;
        }
    </style>
</head>
<body>
    <div id="box2" style="width: 300px;height: 300px; background-color: blueviolet;"></div>
    <div id="box1">
        <img src="/images/08.jpg" style="width: 100px;">
    </div>

</body>
</html>
<script>
    /*
        使 div可以跟随鼠标移动
    */
    var box1 = document.getElementById("box1");
    document.onmousemove=function(event){

        // 解决兼容性问题
        event = event || window.event;

        event.cancelBubble = true;
        // 获取鼠标坐标
        /*
            clientX 和 clientY ⭐📌
                用于获取鼠标在当前的可见窗口的坐标
                div 的偏移量，是相对于整个页面的

            pageX 和 pageY  ⭐📌
                可以用于获取鼠标相对于当前页面的坐标 
                ❗❗ 但是这两个属性在 IE8 中不支持，所以如果需要兼容，则不要使用
        */
        var scrTop = document.body.scrollTop || document.documentElement.scrollTop;
        var scrLeft = document.body.scrollLeft || document.documentElement.scrollLeft;

        var left = (event.clientX) + scrLeft;
        var top = (event.clientY) + scrTop;
        // alert(document.body.scrollTop);
        // 设置 div的偏移量
        box1.style.left = left+"px";
        box1.style.top = top+"px";

    }

    // 获取 id为box2 的div
    var box2 = document.getElementById("box2");
    box2.onmousemove=function(event){
        event = event || window.event;
        event.cancelBubble = true;
    };
</script>